﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Dao;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.Utils;
using CastingWellEquipmentGUI.View.Pages;
using CastingWellEquipmentGUI.View.UserControls;
using CastingWellEquipmentGUI.ViewModel.Common.Command;
using CastingWellEquipmentGUI.ViewModel.Common.LogTool;
using CastingWellEquipmentGUI.ViewModel.Common.WindowsManager;
using Confluent.Kafka;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using Control = CastingWellEquipmentGUI.Model.Control;

namespace CastingWellEquipmentGUI.ViewModel
{
    /// <summary>
    /// MainViewModel.xaml 的交互逻辑
    /// </summary>
    public partial class MainViewModel : ViewModelBase
    {

        /// <summary>
        /// 当前ViewModel标签数据同步线程
        /// </summary>
        private Thread TagInfoSyncThread;
        /// <summary>
        /// 刷新报警信息线程
        /// </summary>
        private Thread AlarmThread;
        /// <summary>
        /// 与网关服务器链接状态侦听线程
        /// </summary>
        private Thread CommunicationStatusListeningWithGatewayThread;

        private Visibility _CloseNetVisibility;

        public Visibility CloseNetVisibility
        {
            get { return _CloseNetVisibility; }
            set
            {

                if (value == Visibility.Visible)
                {
                    IsConnectVisibility = Visibility.Hidden;
                }
                else if (value == Visibility.Hidden)
                {
                    IsConnectVisibility = Visibility.Visible;
                }
                _CloseNetVisibility = value;
                RaisePropertyChanged("CloseNetVisibility");
            }
        }
        private Visibility _IsConnectVisibility;

        public Visibility IsConnectVisibility
        {
            get { return _IsConnectVisibility; }
            set
            {
                _IsConnectVisibility = value;
                RaisePropertyChanged("IsConnectVisibility");
            }
        }
        //报警消息
        private IConsumer<string, object> AlarmConsumer = KafkaHelper.GetAlarmConsumer();
        //等待Kafaka标签值变更消息
        private IConsumer<string, object> KafkaConsumer = KafkaHelper.GetConsumer();
        //等待Kafaka改变标签值结果的消息
        private IConsumer<string, object> KafkaConsumerOfChangeValue = KafkaHelper.GetConsumerChangeValue();
        public User LoginUser
        {
            get { return LogTool.CurrentUser; }
        }
        private string _SystemStatus;
        /// <summary>
        /// 系统运行状态
        /// </summary>
        public string SystemStatus
        {
            get
            {
                if (SystemConfig.SystemStatus != null)
                {

                    _SystemStatus = SystemConfig.SystemStatus;
                }
                return _SystemStatus;
            }
        }
        /// <summary>
        /// 铸造编号
        /// </summary>
        public string CastingNo
        {
            get { return SystemConfig.GetCastingNo(); }
            set
            {
                SystemConfig.SetCastingNo(value);
                RaisePropertyChanged("_CastingNo");
            }
        }

        public string Label_CastingTime
        {
            get { return TagTool.GetTagValueByFormNameAndControlName("Main", "Label_CastingTime"); }
        }

        public string Label_CoolingTime
        {
            get { return TagTool.GetTagValueByFormNameAndControlName("Main", "Label_CoolingTime"); }
        }

        public string Label_HoldTime
        {
            get { return TagTool.GetTagValueByFormNameAndControlName("Main", "Label_HoldTime"); }
        }

        /// <summary>
        /// 系统状态
        /// </summary>
        public string SystemState
        {
            get { return SystemConfig.systemState; }
            set
            {
                SystemConfig.systemState = value;
                SetSystemStateSyncUI(SystemConfig.systemState);
                RaisePropertyChanged("SystemState");
            }
        }

        /// <summary>
        /// 状态切换面板闲置是否选中
        /// </summary>
        private bool _SyatemStateButtonLeisureTimeIsChecked;
        /// <summary>
        /// 状态切换面板闲置是否选中
        /// </summary>
        public bool SyatemStateButtonLeisureTimeIsChecked
        {
            get { return _SyatemStateButtonLeisureTimeIsChecked; }
            set
            {
                _SyatemStateButtonLeisureTimeIsChecked = value;
                RaisePropertyChanged("SyatemStateButtonLeisureTimeIsChecked");
            }
        }

        /// <summary>
        /// 状态切换面板预检测是否选中
        /// </summary>
        private bool _SyatemStateButtonPreCheckIsChecked;
        /// <summary>
        /// 状态切换面板预检测是否选中
        /// </summary>
        public bool SyatemStateButtonPreCheckIsChecked
        {
            get { return _SyatemStateButtonPreCheckIsChecked; }
            set
            {
                _SyatemStateButtonPreCheckIsChecked = value;
                RaisePropertyChanged("SyatemStateButtonPreCheckIsChecked");
            }
        }

        /// <summary>
        /// 状态切换面板提前结束铸造是否选中
        /// </summary>
        private bool _SyatemStateButtonEarlyEndOfCastingIsChecked;
        /// <summary>
        /// 状态切换面板提前结束铸造是否选中
        /// </summary>
        public bool SyatemStateButtonEarlyEndOfCastingIsChecked
        {
            get { return _SyatemStateButtonEarlyEndOfCastingIsChecked; }
            set
            {
                _SyatemStateButtonEarlyEndOfCastingIsChecked = value;
                RaisePropertyChanged("SyatemStateButtonEarlyEndOfCastingIsChecked");
            }
        }
        /// <summary>
        /// 状态切换面板可见许可是否选中
        /// </summary>
        private bool _SyatemStateButtonVisibleLicenseIsChecked;
        /// <summary>
        /// 状态切换面板可见许可是否选中
        /// </summary>
        public bool SyatemStateButtonVisibleLicenseIsChecked
        {
            get { return _SyatemStateButtonVisibleLicenseIsChecked; }
            set
            {
                _SyatemStateButtonVisibleLicenseIsChecked = value;
                RaisePropertyChanged("SyatemStateButtonVisibleLicenseIsChecked");
            }
        }

        /// <summary>
        /// 状态切换面板启动铸造测试是否选中
        /// </summary>
        private bool _SyatemStateButtonStartCastingTestIsChecked;
        /// <summary>
        /// 状态切换面板启动铸造测试是否选中
        /// </summary>
        public bool SyatemStateButtonStartCastingTestIsChecked
        {
            get { return _SyatemStateButtonStartCastingTestIsChecked; }
            set
            {
                _SyatemStateButtonStartCastingTestIsChecked = value;
                RaisePropertyChanged("SyatemStateButtonStartCastingTestIsChecked");
            }
        }

        /// <summary>
        /// 状态切换面板停止铸造测试是否选中
        /// </summary>
        private bool _SyatemStateButtonStopCastingTestIsChecked;
        /// <summary>
        /// 状态切换面板停止铸造测试是否选中
        /// </summary>
        public bool SyatemStateButtonStopCastingTestIsChecked
        {
            get { return _SyatemStateButtonStopCastingTestIsChecked; }
            set
            {
                _SyatemStateButtonStopCastingTestIsChecked = value;
                RaisePropertyChanged("SyatemStateButtonStopCastingTestIsChecked");
            }
        }

        private DispatcherTimer displayTimeTimer;

        private string _CurrentDateTime;

        public string CurrentDateTime
        {
            get { return _CurrentDateTime; }
            set
            {
                _CurrentDateTime = value;
                RaisePropertyChanged("CurrentDateTime");
            }
        }
        /// <summary>
        /// 警报集合
        /// </summary>
        private ObservableCollection<AlarmModel> _Alarms = new ObservableCollection<AlarmModel>();
        /// <summary>
        /// 警报集合
        /// </summary>
        public ObservableCollection<AlarmModel> Alarms
        {
            get { return _Alarms; }
            set
            {
                _Alarms = value;
                RaisePropertyChanged("Alarms");
            }
        }

        private bool _ServerConnectionStatus;
        public bool ServerConnectionStatus
        {
            get { return _ServerConnectionStatus; }
            set
            {
                _ServerConnectionStatus = value;
                RaisePropertyChanged("ServerConnectionStatus");
            }
        }

        /// <summary>
        /// 切换系统状态
        /// </summary>
        public DelegateCommand SwitchSystemStateCommand { get; set; }
        /// <summary>
        /// 退出程序命令
        /// </summary>
        public DelegateCommand ExitApplicationCommand { get; set; }
        /// <summary>
        /// 退出程序命令
        /// </summary>
        public DelegateCommand CloseAppCommand { get; set; }
        /// <summary>
        /// 跳转页面名称
        /// </summary>
        public DelegateCommand GoToPageCommand { get; set; }
        /// <summary>
        /// 隐藏模式切换面板
        /// </summary>
        public DelegateCommand HideSwitchSystemPanelWindowCommand { get; set; }
        /// <summary>
        /// 设置系统状态命令
        /// </summary>
        public DelegateCommand SetSystemStateCommand { get; set; }

        /// <summary>
        /// 主页名称
        /// </summary>
        private string MainName;



        private Frame _MainContent;
        public Frame MainContent
        {
            get
            {

                if (_MainContent == null)
                {
                    _MainContent = new Frame() { Content = EquipmentOverviewPage.Instance };
                    MainName = "EquipmentOverviewPage";
                }
                return _MainContent;
            }
            set
            {
                _MainContent = value;
                RaisePropertyChanged("MainContent");
            }
        }
        /// <summary>
        /// 历史记录集合
        /// </summary>
        private List<HistoryFram> HistoryFrame = new List<HistoryFram>();
        /// <summary>
        /// 下一页时添加历史记录
        /// </summary>
        private void AddHistoryFrame()
        {
            if (HistoryFrame.Count > 0)
            {
                if (HistoryFrame.Last().Name != MainName)
                {
                    HistoryFrame.Add(new HistoryFram
                    {
                        Name = MainName,
                        FrameModel = MainContent,
                        OrderNo = HistoryFrame.Last().OrderNo + 1
                    });
                }
            }
            else
            {
                HistoryFrame.Add(new HistoryFram
                {
                    Name = MainName,
                    FrameModel = MainContent,
                    OrderNo = 1
                });
            }

        }
        /// <summary>
        /// 返回上一页
        /// </summary>
        private void GoPrevPage()
        {
            if (HistoryFrame.Count > 0)
            {
                MainName = HistoryFrame.Last().Name;
                MainContent = HistoryFrame.Last().FrameModel;
                HistoryFrame.Remove(HistoryFrame.Last());
            }

        }



        public MainViewModel()
        {

            TagInfoSyncThread = new Thread(SyncThreadFunc);
            TagInfoSyncThread.SetApartmentState(ApartmentState.STA);
            TagInfoSyncThread.IsBackground = true;
            TagInfoSyncThread.Start();

            // BUG暂时注释掉心跳
            //CommunicationStatusListeningWithGatewayThread = new Thread(CommunicationStatusListeningWithGatewayFunc);
            //CommunicationStatusListeningWithGatewayThread.SetApartmentState(ApartmentState.STA);
            //CommunicationStatusListeningWithGatewayThread.IsBackground = true;
            //CommunicationStatusListeningWithGatewayThread.Start();

            AlarmThread = new Thread(AlarmFunc);
            AlarmThread.SetApartmentState(ApartmentState.STA);
            AlarmThread.IsBackground = true;
            AlarmThread.Start();

            CloseAppCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(CloseAppHandler)
            };

            GoToPageCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ChangeTabHandler)
            };
            ExitApplicationCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(ExitApplicationHandler)
            };
            SwitchSystemStateCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SwitchSystemStateHandler)
            };
            HideSwitchSystemPanelWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideSwitchSystemPanelWindowHandler)
            };
            SetSystemStateCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SetSystemStateHandler)
            };

            //切换子页面本窗体
            Messenger.Default.Register<string>(this, "GoToPage", (message) =>
            {
                GoToPageCommand.ExecuteActionObj(message);
            });
            Alarms = new ObservableCollection<AlarmModel>();
            displayTimeTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            displayTimeTimer.Tick += DisplayTimeTimer_Tick;
            displayTimeTimer.Start();
            ServerConnectionStatus = true;
            SystemState = "闲置";
            CloseNetVisibility = Visibility.Hidden;
        }
        /// <summary>
        /// 与网关服务器链接状态侦听线程方法
        /// </summary>
        private void CommunicationStatusListeningWithGatewayFunc()
        {
            // 心跳失败次数
            int WaitingTime = 0;
            // 获取心跳涉及标签信息
            string sql = "SELECT  ControlName , ControlExplain , TagInfoId " +
                "FROM    dbo.Control a " +
                "        LEFT JOIN dbo.ControlAndTagInfo b ON a.ControlId = b.ControlId " +
                "WHERE   ControlName IN ( 'Button_XinTiao', 'Button_Alarm' ) ORDER BY ControlExplain DESC;";
            List<HeartBeatTagModel> conditions = DapperToolsThisSystem.Query<HeartBeatTagModel>(sql);
            int sendXinTiaoTagId = conditions[0].TagInfoId;
            int receiveXinTiaoTagId = conditions[1].TagInfoId;
            // 初始化消费者
            KafkaHelper.GetConsumerHeartBeat();
            while (true)
            {
                // 先消耗掉心跳结果队列中的消息
                while (true)
                {
                    var resultother = KafkaHelper.consumerHeartBeat.Consume(1000);
                    if (resultother == null)
                    {
                        break;
                    }
                }
                /**     
                 * 心跳业务逻辑：
                 * 1、给网关特定标签（Xin_Tiao标签）发送消息，每秒发送一次，消息连续发送3次失败判定网络故障。
                 * 2、网关收到消息后，往PLC Xin_Tiao写值1，写值成功后读取PLC Alarm标签值，并将Alarm标签值通过Kafka消息队列发送回本机。
                 * 3、规约当Alarm标签值=1时，网络连接失败，如果连续3次Alarm标签值=1则判定为网络连接故障。心跳1次2秒内接收不到网关回应算一次失败。
                 * 4、当Alarm标签值=0时，认为网络连接正常。
                 * **/

                // 发送消息给网关
                HeartBeatInfoModel heartBeat = new HeartBeatInfoModel
                {
                    XinTiaoId = sendXinTiaoTagId,
                    AlarmId = receiveXinTiaoTagId,
                    Guid = Guid.NewGuid().ToString()
                };
                if (KafkaHelper.SendHeartBeat(heartBeat))
                {
                    // 发送成功
                    // 阻塞消费Alarm值，阻塞1000毫秒
                    var result = KafkaHelper.consumerHeartBeat.Consume(1000);
                    if (result != null)
                    {
                        // 消费掉
                        KafkaHelper.consumerHeartBeat.Commit(result);
                        HeartBeatResultModel heartBeatResult = JsonConvert.DeserializeObject<HeartBeatResultModel>(result.Message.Value.ToString());
                        if (heartBeatResult.Guid == heartBeat.Guid && heartBeatResult.AlarmValue == 1)
                        {
                            // 心跳失败
                            WaitingTime++;
                        }
                        else if (heartBeatResult.Guid == heartBeat.Guid && heartBeatResult.AlarmValue == 0)
                        {
                            // 心跳成功
                            WaitingTime = 0;
                        }
                    }
                    else
                    {
                        WaitingTime++;
                    }
                }
                else
                {
                    // 发送失败
                    WaitingTime++;
                }
                // 如果3次心跳失败即判定网络故障
                if (WaitingTime >= 3)
                {
                    SystemConfig.SystemStatus = "网络中断";
                    CloseNetVisibility = Visibility.Visible;
                    RaisePropertyChanged("SystemStatus");
                }
                else
                {
                    SystemConfig.SystemStatus = "网络正常";
                    CloseNetVisibility = Visibility.Hidden;
                    RaisePropertyChanged("SystemStatus");
                }
            }
        }


        /// <summary>
        /// 标签数据同步
        /// </summary>
        private void SyncThreadFunc()
        {
            HashSet<Control> tempHashSet = new HashSet<Control>();
            for (int i = 0; i < LogTool.CurrentUser.Roles.Count; i++)
            {
                for (int j = 0; j < LogTool.CurrentUser.Roles[i].Permissions.Count; j++)
                {
                    if (LogTool.CurrentUser.Roles[i].Permissions[j].PControl == null)
                    {
                        continue;
                    }
                    tempHashSet.Add(LogTool.CurrentUser.Roles[i].Permissions[j].PControl);
                }
            }
            if (tempHashSet.Count > 0)
            {
                DoChanged(tempHashSet);
            }

            while (true)
            {
                if (SystemConfig.SystemStatus == "网络中断")
                {
                    Thread.Sleep(100);
                    break;
                }
                if (ThreadController.RoundBarLaunderThreadState)
                {
                    //开始消费
                    var result = KafkaConsumer.Consume();
                    //如果是标签值变动
                    if (result.Message.Key == "TagChange")
                    {
                        //手动提交
                        KafkaConsumer.Commit(result);
                        //获取消息内容
                        string tagId = result.Message.Value.ToString();
                        HashSet<Control> hashSet = new HashSet<Control>();
                        HashSet<Control> hashSetSwitchSystemPanelWindow = KafkaHelper.UpdateCurrentUserTagValue(Int32.Parse(tagId), KafkaHelper.GetTagValueByKey(tagId.ToString()), "SwitchSystemPanelWindow");
                        HashSet<Control> hashSetMain = KafkaHelper.UpdateCurrentUserTagValue(Int32.Parse(tagId), KafkaHelper.GetTagValueByKey(tagId.ToString()), "Main");
                        foreach (var item in hashSetSwitchSystemPanelWindow)
                        {
                            hashSet.Add(item);
                        }
                        foreach (var item in hashSetMain)
                        {
                            hashSet.Add(item);
                        }
                        if (hashSet != null)
                        {
                            DoChanged(hashSet);
                        }
                    }
                }
                Thread.Sleep(100);
            }
        }


        /// <summary>
        /// 执行动作
        /// </summary>
        /// <param name="hashSet"></param>
        private void DoChanged(HashSet<Control> hashSet)
        {
            //遍历返回的控件信息刷新对应的控件
            foreach (Control item in hashSet)
            {
                switch (item.ControlName)
                {
                    case "RadioButton_LeisureTime":
                        if (TagTool.GetTagValueByFormNameAndControlName("SwitchSystemPanelWindow", item.ControlName) != "false")
                        {
                            SetSystemStateSyncUI("闲置");
                        }
                        else
                        {
                            SyatemStateButtonLeisureTimeIsChecked = false;
                        }
                        break;
                    case "RadioButton_PreCheck":

                        if (TagTool.GetTagValueByFormNameAndControlName("SwitchSystemPanelWindow", item.ControlName) != "false")
                        {
                            SetSystemStateSyncUI("预检测");
                        }
                        else
                        {
                            SyatemStateButtonPreCheckIsChecked = false;
                        }
                        break;
                    case "RadioButton_EarlyEndOfCasting":

                        if (TagTool.GetTagValueByFormNameAndControlName("SwitchSystemPanelWindow", item.ControlName) != "false")
                        {
                            SetSystemStateSyncUI("提前结束铸造");
                        }
                        else
                        {
                            SyatemStateButtonEarlyEndOfCastingIsChecked = false;
                        }
                        break;
                    case "RadioButton_VisibleLicense":

                        if (TagTool.GetTagValueByFormNameAndControlName("SwitchSystemPanelWindow", item.ControlName) != "false")
                        {
                            SetSystemStateSyncUI("可见许可");
                        }
                        else
                        {
                            SyatemStateButtonVisibleLicenseIsChecked = false;
                        }
                        break;
                    case "RadioButton_StartCastingTest":

                        if (TagTool.GetTagValueByFormNameAndControlName("SwitchSystemPanelWindow", item.ControlName) != "false")
                        {
                            SetSystemStateSyncUI("启动铸造测试");
                        }
                        else
                        {
                            SyatemStateButtonStartCastingTestIsChecked = false;
                        }
                        break;
                    case "RadioButton_StopCastingTest":
                        if (TagTool.GetTagValueByFormNameAndControlName("SwitchSystemPanelWindow", item.ControlName) != "false")
                        {
                            SetSystemStateSyncUI("停止铸造测试");
                        }
                        else
                        {
                            SyatemStateButtonStopCastingTestIsChecked = false;
                        }
                        break;
                    default:
                        RaisePropertyChanged(item.ControlName);
                        break;
                }
            }
        }


        /// <summary>
        /// 根据系统状态同步UI
        /// </summary>
        private void SetSystemStateSyncUI(string SystemStateVal)
        {
            SystemConfig.systemState = SystemStateVal;
            SyatemStateButtonLeisureTimeIsChecked = false;
            SyatemStateButtonPreCheckIsChecked = false;
            SyatemStateButtonEarlyEndOfCastingIsChecked = false;
            SyatemStateButtonVisibleLicenseIsChecked = false;
            SyatemStateButtonStartCastingTestIsChecked = false;
            SyatemStateButtonStopCastingTestIsChecked = false;
            switch (SystemStateVal)
            {
                case "闲置":
                    SyatemStateButtonLeisureTimeIsChecked = true;
                    break;
                case "预检测":
                    SyatemStateButtonPreCheckIsChecked = true;
                    break;
                case "提前结束铸造":
                    SyatemStateButtonEarlyEndOfCastingIsChecked = true;
                    break;
                case "可见许可":
                    SyatemStateButtonVisibleLicenseIsChecked = true;
                    break;
                case "启动铸造测试":
                    SyatemStateButtonStartCastingTestIsChecked = true;
                    break;
                case "停止铸造测试":
                    SyatemStateButtonStopCastingTestIsChecked = true;
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// 设置系统状态命令处理器
        /// </summary>
        /// <param name="obj"></param>
        private void SetSystemStateHandler(object obj)
        {
            SystemState = obj.ToString();
            int tagId = 0;
            switch (SystemState)
            {
                case "闲置":
                    tagId = SystemConfig.QueryTagIdByControlNameAndFormName("SwitchSystemPanelWindow", "RadioButton_LeisureTime");
                    break;
                case "预检测":
                    // 跳转到预检测画面
                    SetSystemStateSyncUI(SystemState);
                    ChangeTabHandler("PreCheckPage");
                    break;
                case "提前结束铸造":
                    tagId = SystemConfig.QueryTagIdByControlNameAndFormName("SwitchSystemPanelWindow", "RadioButton_EarlyEndOfCasting");
                    break;
                case "可见许可":
                    tagId = SystemConfig.QueryTagIdByControlNameAndFormName("SwitchSystemPanelWindow", "RadioButton_VisibleLicense");
                    break;
                case "启动铸造测试":
                    tagId = SystemConfig.QueryTagIdByControlNameAndFormName("SwitchSystemPanelWindow", "RadioButton_StartCastingTest");
                    break;
                case "停止铸造测试":
                    tagId = SystemConfig.QueryTagIdByControlNameAndFormName("SwitchSystemPanelWindow", "RadioButton_StopCastingTest");
                    break;

            }
            if (tagId != 0)
            {
                BusinessCmd setTagValueMsg = new BusinessCmd
                {
                    Guid = Guid.NewGuid().ToString(),
                    BusinessCmdCode = 3,
                    TagId = tagId,
                    TagValue = "true"
                };
                // 发送按钮消息
                if (KafkaHelper.SendGatewayBusinessCmd(setTagValueMsg))
                {
                    SetSystemStateSyncUI(SystemState);
                }
            }
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideSwitchSystemPanelWindow"));
        }

        /// <summary>
        /// 隐藏系统状态选择面板
        /// </summary>
        /// <param name="obj"></param>
        private void HideSwitchSystemPanelWindowHandler(object obj)
        {
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideSwitchSystemPanelWindow"));
        }


        /// <summary>
        /// 切换系统状态命令的处理器
        /// </summary>
        /// <param name="obj"></param>
        private void SwitchSystemStateHandler(object obj)
        {
            WindowManager.ShowDialog("SwitchSystemPanelWindow", "");
        }
        /// <summary>
        /// 刷新报警
        /// </summary>
        private void AlarmFunc()
        {
            while (true)
            {
                if (SystemConfig.SystemStatus == "网络中断")
                {
                    Thread.Sleep(100);
                    break;
                }
                //开始消费
                var result = AlarmConsumer.Consume();
                if (result != null)
                {
                    AlarmConsumer.Commit(result);
                    Alarms = KafkaHelper.GetAlarms();
                }
                Thread.Sleep(1000);
            }
            //ObservableCollection<AlarmModel> tempAlarms = Alarms;
            //tempAlarms.Add(new AlarmModel
            //{
            //    OrderNo = 1,
            //    AlarmLevel = "一级报警",
            //    AlarmContent = "测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试",
            //    AlarmDateTime = DateTime.Now
            //}
            //);
            //Alarms = tempAlarms;
        }
        /// <summary>
        /// 显示时间方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DisplayTimeTimer_Tick(object sender, EventArgs e)
        {
            CurrentDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        /// <summary>
        /// 退出程序命令处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void CloseAppHandler(object obj)
        {
            Environment.Exit(0);
        }


        /// <summary>
        /// 改变Tab页事件处理器
        /// </summary>
        /// <param name="o"></param>
        private void ChangeTabHandler(object obj)
        {
            if (SystemConfig.SystemStatus == "网络中断")
            {
                return;
            }
            string parameter = obj.ToString();
            if (SystemConfig.equipmentCategory == "圆棒")
            {
                switch (parameter)
                {
                    case "EquipmentOverviewPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = EquipmentOverviewPage.Instance };
                        MainName = parameter;
                        break;
                    //case "TrendChartPage":
                    //    AddHistoryFrame();
                    //    MainContent = new Frame() { Content = TrendChartPage.Instance };
                    //    MainName = parameter;
                    //    break;
                    case "LaunderPage":
                        Messenger.Default.Send<string>("LaunderPage", "LaunderPageShowPageTitle");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = LaunderPage.Instance };
                        MainName = parameter;
                        break;
                    case "HoldingFurnacePage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = HoldingFurnacePage.Instance };
                        MainName = parameter;
                        break;
                    case "WireFeederPage":
                        Messenger.Default.Send<string>(null, parameter + "_DoChange");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = WireFeederPage.Instance };
                        MainName = parameter;
                        break;
                    case "DegassingTankPage":
                        Messenger.Default.Send<string>(null, parameter + "_DoChange");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = DegassingTankPage.Instance };
                        MainName = parameter;
                        break;
                    case "CastWellPublicAuxiliaryPage":
                        Messenger.Default.Send<string>(null, parameter + "_DoChange");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = CastWellPublicAuxiliaryPage.Instance };
                        MainName = parameter;
                        break;
                    case "LubricationSystemPage":
                        Messenger.Default.Send<string>(null, parameter + "_DoChange");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = LubricationSystemPage.Instance };
                        MainName = parameter;
                        break;
                    case "CastWellPublicPage":
                        Messenger.Default.Send<string>(null, parameter + "_DoChange");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = CastWellPublicPage.Instance };
                        MainName = parameter;
                        break;
                    case "HydraulicSystemPage":
                        Messenger.Default.Send<string>(null, parameter + "_DoChange");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = HydraulicSystemPage.Instance };
                        MainName = parameter;
                        break;
                    case "WaterSupplySystemPage":
                        Messenger.Default.Send<string>(null, parameter + "_DoChange");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = WaterSupplySystemPage.Instance };
                        MainName = parameter;
                        break;
                    case "DrainageSystemPage":
                        Messenger.Default.Send<string>(null, parameter + "_DoChange");
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = DrainageSystemPage.Instance };
                        MainName = parameter;
                        break;
                    case "PreCheckPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = PreCheckPage.Instance };
                        MainName = parameter;
                        break;

                    case "RecipeSelectionPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = RecipeSelectionPage.Instance };
                        MainName = parameter;
                        break;
                    case "RecipeManagementPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = RecipeManagementPage.Instance };
                        MainName = parameter;
                        break;
                    case "CreateRecipePage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = CreateRecipePage.Instance };
                        MainName = parameter;
                        break;
                    case "ViewRecipePage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = ViewRecipePage.Instance };
                        MainName = parameter;
                        break;
                    case "EditRecipePage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = EditRecipePage.Instance };
                        MainName = parameter;
                        break;
                    case "RecipeSelectionListPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = RecipeSelectionListPage.Instance };
                        MainName = parameter;
                        break;
                    case "CastingRecordPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = CastingRecordPage.Instance };
                        MainName = parameter;
                        break;
                    case "AlarmQueryPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = AlarmQueryPage.Instance };
                        MainName = parameter;
                        break;
                    case "AlarmHistoryQueryPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = AlarmHistoryQueryPage.Instance };
                        MainName = parameter;
                        break;
                    case "SettingMenuPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = SettingMenuPage.Instance };
                        MainName = parameter;
                        break;
                    case "TrendChartPage":
                        Process.Start(AppDomain.CurrentDomain.BaseDirectory + "BeeColorPicker.exe");
                        break;
                    case "NetConnectPage":
                        AddHistoryFrame();
                        MainContent = new Frame() { Content = NetConnectPage.Instance };
                        MainName = parameter;
                        break;
                    case "PrevPage":
                        GoPrevPage();
                        if (MainName == "RecipeSelectionListPage")
                        {
                            Messenger.Default.Send("", "RecipeSelectionPageRefurbish");
                        }
                        else if (MainName == "CastingRecordPage")
                        {
                            Messenger.Default.Send("", "CastingRecordPageRefurbish");
                        }
                        else if (MainName == "LaunderPage")
                        {
                            Messenger.Default.Send<string>("LaunderPage", "LaunderPageShowPageTitle");
                        }
                        break;
                }
                ThreadController.ControllerThreadState(MainName);
            }

        }
        /// <summary>
        /// 退出程序处理方法
        /// </summary>
        /// <param name="obj"></param>
        private void ExitApplicationHandler(object obj)
        {
            WindowManager.ShowDialog("ExitPanel", null);
        }

    }
}
